package controller;

import model.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "UserRigister", value = "/user_rigister")
public class UserRigisterServlet extends HttpServlet {
    UserService us = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;Charset=utf-8");
        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setEmail(request.getParameter("email"));
        user.setPassword(request.getParameter("password"));
        user.setName(request.getParameter("name"));
        user.setPhone(request.getParameter("phone"));
        user.setAddress(request.getParameter("address"));
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;Charset=utf-8");
            if (us.register(user)) {
                request.getSession().setAttribute("msg", "注册成功，请登录！");
                request.getRequestDispatcher("user_login.jsp").forward(request, response);
            } else {
                request.getSession().setAttribute("msg", "用户名或邮箱重复，请重新填写！");
                request.getRequestDispatcher("user_register.jsp").forward(request, response);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
